"""Tests for music generation functionality."""
import pytest
from unittest.mock import Mock, patch, MagicMock
from datetime import datetime
from app.tasks.music_tasks import generate_and_save_music
from app.models.music import Music


class TestMusicGenerationTask:
    """Tests for the music generation Celery task."""
    
    def test_generate_and_save_music_success(self, app):
        """Test successful music generation and storage."""
        with app.app_context():
            # Arrange
            user_id = "test_user_123"
            session_id = "test_session_456"
            poi_data = {
                'id': 'poi_789',
                'name': '测试景点',
                'category': '公园',
                'description': '一个美丽的公园',
                'location': {'latitude': 39.9, 'longitude': 116.4}
            }
            weather_data = {
                'temperature': 25.0,
                'condition': '晴',
                'humidity': 60,
                'wind_speed': 5.0,
                'aqi': 50,
                'timestamp': datetime.utcnow().isoformat()
            }
            mood = 'relaxed'
            
            # Mock the AI service and storage service
            mock_audio_bytes = b'fake_music_data'
            mock_file_url = 'https://example.com/music/test.mp3'
            
            with patch('app.tasks.music_tasks.AIGenerationService') as MockAI, \
                 patch('app.tasks.music_tasks.StorageService') as MockStorage:
                
                # Configure mocks
                mock_ai_instance = MockAI.return_value
                mock_ai_instance.generate_background_music.return_value = mock_audio_bytes
                
                mock_storage_instance = MockStorage.return_value
                mock_storage_instance.upload_audio.return_value = mock_file_url
                
                # Act
                result = generate_and_save_music(
                    user_id=user_id,
                    session_id=session_id,
                    poi_data=poi_data,
                    weather_data=weather_data,
                    mood=mood
                )
            
            # Assert
            assert result['success'] is True
            assert 'music_id' in result
            assert result['file_url'] == mock_file_url
    
    def test_generate_and_save_music_failure(self, app):
        """Test music generation failure handling."""
        with app.app_context():
            # Arrange
            user_id = "test_user_123"
            session_id = "test_session_456"
            poi_data = {
                'id': 'poi_789',
                'name': '测试景点',
                'category': '公园',
                'description': '一个美丽的公园',
                'location': {'latitude': 39.9, 'longitude': 116.4}
            }
            weather_data = {
                'temperature': 25.0,
                'condition': '晴',
                'humidity': 60,
                'wind_speed': 5.0,
                'aqi': 50,
                'timestamp': datetime.utcnow().isoformat()
            }
            mood = 'relaxed'
            
            # Mock the AI service to raise an exception
            with patch('app.tasks.music_tasks.AIGenerationService') as MockAI:
                mock_ai_instance = MockAI.return_value
                mock_ai_instance.generate_background_music.side_effect = Exception("API Error")
                
                # Act
                result = generate_and_save_music(
                    user_id=user_id,
                    session_id=session_id,
                    poi_data=poi_data,
                    weather_data=weather_data,
                    mood=mood
                )
            
            # Assert
            assert result['success'] is False
            assert 'error' in result
            assert 'API Error' in result['error']
